<?php
/*
* @User: 小灰灰 <762229008@qq.com>
* @Date: 2025-03-05
* @Time: 12:02:24
* @Info: 插件控制器
* Copyright (c) 2022~2025 https://xiaohuihui.cc All rights reserved.
*/

namespace app\admin\controller;

use think\addons\AddonException;
use think\addons\Service;
use app\common\service\admin\AuthService;
use think\facade\Config;
use think\facade\Db;

class Addon extends Base
{

//初始化
    protected function initialize()
    {
        parent::initialize();
        $admin_id = cmf_get_admin_id();
        if ( ! AuthService::instance()->isSuperAdmin($admin_id) && in_array($this->request->action(),
                ['install', 'uninstall', 'local'])) {
            $this->error('非超级管理员禁止操作！');
        }
    }

    public function index()
    {
        $type   = $this->request->param("type", 'online');
        $limit  = $this->request->param("limit/d");
        $page   = $this->request->param("page/d", 1);
        $search = $this->request->param("search", '', 'strip_tags,htmlspecialchars');

        if ($this->request->isAjax()) {
            if ($type == 'local') {
                // 本地插件
                $addons = get_addon_list();
                if ($search) {
                    $addons = array_filter($addons, function ($v) use ($search) {
                        return stripos($v['name'], $search) !== false || stripos($v['title'],
                                $search) !== false || stripos($v['description'], $search) !== false;
                    });
                }
                foreach ($addons as $k => $v) {
                    $config              = get_addon_config($v['name']);
                    $v['config']         = $config ? 1 : 0;
                    $addons[$k]['addon'] = $v;
                }
                $count = count($addons);
                if ($limit) {
                    $addons = array_slice($addons, ($page - 1) * $limit, $limit);
                }
                $result = ["code" => 0, "msg" => $search, "data" => $addons, 'count' => $count, 'keyword' => $search];
            } else {
                // 在线插件
                $list         = $this->getAddonList($search, $page, $limit);
                $onlineaddons = $list['list'] ?? [];
                $category     = $list['category'] ?? [];
                $count        = $list['count'] ?? -1;
                //本地插件
                $addons = get_addon_list();
                foreach ($addons as &$v) {
                    $config      = get_addon_config($v['name']);
                    $v['config'] = $config ? 1 : 0;
                }
                foreach ($onlineaddons as &$item) {
                    $item['addon'] = $addons[$item['name']] ?? '';
                }
                $result = [
                    "code"     => 0,
                    "msg"      => $search,
                    "data"     => $onlineaddons,
                    "category" => $category,
                    'count'    => $count,
                    'keyword'  => $search
                ];
            }

            return json($result);
        }
        $this->assign('type', $type);
        $this->assign('search', $search);

        return $this->fetch();
    }

    /**
     * 设置插件页面
     */
    public function config($name = null)
    {
        $file = "E:\www\huicmf_tp61_new\public\/uploads/files/20250307/7d0b97bf26530bfe6fa2a88e6f584165.zip";
        if ( ! $file || ! $file instanceof \think\File) {
            throw new \Exception('没有文件上传或服务器上传限制');
        }
    }

    /**
     * 禁用启用.
     */
    public function status()
    {
        $name   = $this->request->param('name');
        $action = $this->request->param('action');
        $force  = $this->request->post("force/d");
        if ( ! $name) {
            $this->error('参数不得为空！');
        }
        if ( ! preg_match('/^[a-zA-Z0-9]+$/', $name)) {
            $this->error('插件名称不正确');
        }
        try {
            $action = $action == 'enable' ? $action : 'disable';
            //调用启用、禁用的方法
            Service::$action($name, $force);
        } catch (AddonException $e) {
            $this->result($e->getData(), $e->getCode(), $e->getMessage());
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('操作成功');
    }

    /**
     * 安装插件
     */
    public function install()
    {

    }

    /**
     * 卸载插件
     */
    public function uninstall()
    {
        $name       = $this->request->param('name');
        $force      = $this->request->param("force/d");
        $droptables = $this->request->param("droptables/d");
        if (empty($name)) {
            $this->error('请选择需要安装的插件！');
        }
        if ( ! preg_match('/^[a-zA-Z0-9]+$/', $name)) {
            $this->error('插件标识错误！');
        }
        //只有开启调试且为超级管理员才允许删除相关数据库
        $tables   = [];
        $admin_id = cmf_get_admin_id();
        if ($droptables && env('APP_DEBUG') && AuthService::instance()->isSuperAdmin($admin_id)) {
            $tables = get_addon_tables($name);
        }
        $info = get_addon_info($name);
        try {
            Service::uninstall($name, $force);
            if ($tables) {
                //$prefix = Config::get('database.prefix');
                //删除插件关联表
                foreach ($tables as $table) {
                    Db::execute("DROP TABLE IF EXISTS `{$table}`");
                }
            }
        } catch (AddonException $e) {
            $this->result($e->getData(), $e->getCode(), $e->getMessage());
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('插件卸载成功！清除浏览器缓存和框架缓存后生效！');
    }

    /**
     * 本地上传
     */
    public function local()
    {
        $file = $this->request->param('file_url');
        try {
            // 检查文件路径是否为空或文件是否存在
            if (empty($file) || ! is_file(public_path().$file)) {
                throw new \Exception('没有文件上传或服务器上传限制');
            }

            // 创建文件对象
            $fileObject = new \think\File(public_path().$file);

            // 调用 Service::local 方法
            $info = Service::local($fileObject);
        } catch (AddonException $e) {
            $this->result($e->getData(), $e->getCode(), $e->getMessage());
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        return json([
            'code' => 200,
            'msg'  => '插件安装成功！清除浏览器缓存和框架缓存后生效！',
            'data' => $info
        ]);
    }

    /**
     * 更新插件
     */
    public function upgrade()
    {

    }

    /**
     * 测试数据
     */
    public function testdata()
    {

    }

    /**
     * 检测
     */
    public function isbuy()
    {

    }

    /**
     * 获取插件相关表
     */
    public function get_table_list()
    {
        $name = $this->request->post("name");
        if ( ! preg_match("/^[a-zA-Z0-9]+$/", $name)) {
            $this->error('插件标识错误！');
        }
        $tables = get_addon_tables($name);
        //$prefix = Config::get('database.prefix');
        $tables = array_values($tables);
        $this->success('', null, ['tables' => $tables]);
    }

    protected function getAddonList($search, $page, $limit)
    {
        $params = [
            'uid'         => $this->request->param('uid/d'),
            'token'       => $this->request->param('token'),
            'category_id' => $this->request->param('category_id/d'),
            'version'     => Config::get('version.huicmf_version'),
            'page'        => $page,
            'limit'       => $limit,
            'search'      => $search,
        ];
        $json   = [];
        try {
            $json = Service::addons($params);
        } catch (\Exception $e) {

        }

        return $json;
    }

}
